<template>
  <div class="login-container">
    <!-- 头部 -->
    <van-nav-bar fixed title="登录页"></van-nav-bar>

    <!-- 表单 -->
    <div class="form">
      <van-form @submit="login">
        <van-field
          v-model="form.username"
          label="用户名"
          placeholder="请输入用户名"
          :rules="rules.username"
        />
        <van-field
          v-model="form.password"
          type="password"
          name="密码"
          label="密码"
          placeholder="请输入密码"
          :rules="rules.password"
        />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit">
            登录
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { login } from '@/api//request.js'
import qs from 'qs'
export default {
  name: 'Login',
  data() {
    return {
      // 表单数据
      form: {
        username: '',
        password: '',
      },
      // 校验规则
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trrigger: 'onBlur',
          },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'onBlur',
          },
        ],
      },
    }
  },
  methods: {
    // 只有表单校验通过后, 才会调用此函数
    async login() {
      const params = qs.stringify({
        ...this.form,
      })
      const { data: res } = await login(params)
      const { status, message, token } = res
      if (status !== 0) {
        return this.$notify({ type: 'danger', message: '登录失败' })
      }

      localStorage.setItem('token', token)
      this.$notify({ type: 'success', message: '登录成功' })
      this.$router.push('/main/home')
    },
  },
}
</script>

<style lang="less" scoped>
.login-container {
  padding-top: 46px;

  .form {
    margin-top: 108px;
  }
}
</style>
